import json
import re
import time

import requests
from twocaptcha import TwoCaptcha

solver = TwoCaptcha('83c6f45a60b4b202f76bb88096ce0bcc')

api_endpoint = "https://api.2captcha.com/createTask"
aws_key = "83c6f45a60b4b202f76bb88096ce0bcc"
api_result = "https://api.2captcha.com/getTaskResult"
capsolver_key = "CAP-147149A8FD7E82B0A83BCD2E317C51AB2D5060780317C5C0488E4DBBFF596609"


def get_captcha_aws(req:dict,proxies):
    #proxies = {'https': 'http://127.0.0.1:7890'}
    query = {
        "clientKey": aws_key,
        "task": {
            "type": "AmazonTaskProxyless",
            "websiteURL": "https://manatuku.com/payments/new",
            "challengeScript": req["challenge_js_url"],
            "captchaScript": req['captcha_url'],
            "websiteKey": req["key"],
            "context": req["context"],
            "iv": req["iv"]
        }
    }
    res = requests.post(url=api_endpoint,json=query,proxies=proxies, verify=False, timeout=10)
    json_data = json.loads(res.text)
    if json_data["taskId"]:
        task_id = json_data["taskId"]
        while True:
           time.sleep(2)

           data = {
                "clientKey": aws_key,
                "taskId": task_id
            }
           task_res = requests.post(url=api_result,json=data,proxies=proxies, verify=False, timeout=10)
           if "processing" in task_res.text:
               continue

           elif "errorDescription" in task_res.text:
               return None
           else:
               json_data = json.loads(task_res.text)
               solution = json_data["solution"]
               return solution
    return None


def capsolver(results):
    proxies = {'https': 'http://127.0.0.1:7890'}
    payload = {
        "clientKey": capsolver_key,
        "task": {
            "type": 'AntiAwsWafTaskProxyLess',
            "websiteURL": "https://manatuku.com/payments/new",
            "awsKey": results["key"],
            "awsIv": results["iv"],
            "awsContext": results["context"],
            "awsChallengeJS":results["challenge_js_url"],

        }
    }

    res = requests.post("https://api.capsolver.com/createTask", json=payload,proxies=proxies, verify=False, timeout=10)
    resp = res.json()
    task_id = resp.get("taskId")
    if not task_id:
        print("Failed to create task:", res.text)
        return
    print(f"Got taskId: {task_id} / Getting result...")

    while True:
        time.sleep(1)  # delay
        payload = {"clientKey": capsolver_key, "taskId": task_id}
        res = requests.post("https://api.capsolver.com/getTaskResult", json=payload,proxies=proxies, verify=False, timeout=10)
        resp = res.json()
        status = resp.get("status")
        if status == "ready":
            return resp.get("solution", {}).get('cookie')
        if status == "failed" or resp.get("errorId"):
            print("Solve failed! response:", res.text)
            return


class ManatSuku:
    def __init__(self, manatsuku_session, aws_waf_token):
        self.manatsuku_session = manatsuku_session
        self.aws_waf_token = aws_waf_token
        self.gmo_payment_token = ''
        self.card_company = ''
        self.holder_name = ''
        self.card_number = ''
        self.expire = ''
        self.proxies = {}

    def getNew(self):
        url = 'https://manatuku.com/payments/new'

        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'referer': 'https://manatuku.com/payments/new',
            'sec-ch-ua': '"Chromium";v="142", "Microsoft Edge";v="142", "Not_A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0'
        }

        cookies = {
            '_manatsuku_session': self.manatsuku_session,
            'aws-waf-token': self.aws_waf_token
        }
        proxies = {'https': 'http://127.0.0.1:7890'}
        try:
            if self.proxies:
                response = requests.get(
                    url,
                    headers=headers,
                    cookies=cookies,
                    proxies=self.proxies,
                    timeout=10
                )
            else:
                response = requests.get(
                    url,
                    headers=headers,
                    cookies=cookies,
                    timeout=10
                )
            response.raise_for_status()
            return response

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {e}")
            return None

    def submi_payment(self, authenticity_token):
        url = 'https://manatuku.com/payments'

        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded',
            'origin': 'https://manatuku.com',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'referer': 'https://manatuku.com/payments/new',
            'sec-ch-ua': '"Chromium";v="142", "Microsoft Edge";v="142", "Not_A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0'
        }

        cookies = {
            'aws-waf-token': self.aws_waf_token,
            '_manatsuku_session': self.manatsuku_session
        }

        data = {
            'utf8': '✓',
            'authenticity_token': authenticity_token,
            'payment_credit_card[type]': 'Payment::CreditCard',
            'payment_credit_card[card_company]': self.card_company,
            'payment_credit_card[card_number]': self.card_number,
            'payment_credit_card[holder_name]': self.holder_name,
            'payment_credit_card[gmo_payment_token]': self.gmo_payment_token
        }

        try:
            if self.proxies:
                response = requests.post(
                    url,
                    headers=headers,
                    cookies=cookies,
                    data=data,
                    proxies=self.proxies,
                    timeout=10
                )
            else:
                response = requests.post(
                    url,
                    headers=headers,
                    cookies=cookies,
                    data=data,
                    timeout=10
                )

            response.raise_for_status()
            # 检查是否是重定向
            if response.history:
                print(f"发生重定向 → 最终URL: {response.url}")
            return response

        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return None

    def set_gmo_payment(self, card_number, holder_name, expire, card_company):
        self.card_number = card_number
        self.holder_name = holder_name
        self.card_company = card_company
        self.expire = expire
        self.gmo_payment_token = getGmoToken(self.card_number, self.holder_name, self.expire)
        return self.gmo_payment_token

    def set_proxies(self, ip, post, user='', password=''):
        if user and password:
            self.proxies = {
                'http': f'http://{user}:{password}@{ip}:{post}',
                'https': f'http://{user}:{password}@{ip}:{post}'
            }
        else:
            self.proxies = {
                'http': f'http://{ip}:{post}',
                'https': f'http://{ip}:{post}'
            }

    def voucherCaptcha(self, url, data):
        proxies = {'https': 'http://127.0.0.1:7890'}
        headers = {
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0",
            'Accept-Encoding': "gzip, deflate, br, zstd",
            'Content-Type': "text/plain",
            'pragma': "no-cache",
            'cache-control': "no-cache",
            'sec-ch-ua-platform': "\"Windows\"",
            'sec-ch-ua': "\"Chromium\";v=\"142\", \"Microsoft Edge\";v=\"142\", \"Not_A Brand\";v=\"99\"",
            'content-type': "text/plain;charset=UTF-8",
            'sec-ch-ua-mobile': "?0",
            'origin': "https://manatuku.com",
            'sec-fetch-site': "cross-site",
            'sec-fetch-mode': "cors",
            'sec-fetch-dest': "empty",
            'referer': "https://manatuku.com/",
            'accept-language': "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            'priority': "u=1, i"
        }
        if self.proxies:
            response = requests.post(url, headers=headers, cookies=data, proxies=self.proxies, timeout=10)
        else:
            response = requests.post(url, headers=headers, json=data)
        if 'token' in response.text:
            res = response.json()
            print(res)
            self.aws_waf_token = res['token']
            return True
        else:
            print(response.text)
            return False

    def main(self):
        new_page = self.getNew()
        new_page_text = new_page.text
        if 'JavaScript is disabled' in new_page_text:
            # time.sleep(20)
            print('触发验证码')
            # print(new_page_text)
            challenge_pattern = r'src="(https?://[^"]*challenge\.js)"'
            key_pattern = r'"key":"([^"]*)"'
            iv_pattern = r'"iv":"([^"]*)"'
            context_pattern = r'"context":"([^"]*)"'
            challenge_url = re.search(challenge_pattern, new_page_text).group(1)
            key = re.search(key_pattern, new_page_text).group(1)
            iv = re.search(iv_pattern, new_page_text).group(1)
            context = re.search(context_pattern, new_page_text).group(1)
            # print("challenge.js:", challenge_url)
            # print("captcha.js:", challenge_url.replace("token", "captcha").replace("challenge", "captcha"))
            # print("key:", key)
            # print("iv:", iv)
            # print("context:", context)
            # result = solver.amazon_waf(key, iv, context, 'https://manatuku.com/payments/new', challenge_script = challenge_url, captcha_script = challenge_url.replace("token", "captcha").replace("challenge", "captcha"),proxy={
            #                        'type': 'HTTP',
            #                        'uri': f'{proxyUsername}:{proxyPassword}@{ip}:{port}'
            #                    })
            req = {"captcha_url": challenge_url.replace("token", "captcha").replace("challenge", "captcha"),
                   "key": key, "iv": iv, "context": context,"challenge_js_url":challenge_url}

            result=capsolver(req)
            print(result)
            result_dict = {
                "aws-waf-token":result
            }
           # print(result['code'])
            vouch = self.voucherCaptcha(challenge_url.replace("challenge.js", "voucher"), result_dict)
            if vouch:
                print('验证码通过')
                return self.main()
            else:
                print('验证码未通过')
                return False
        else:
            print('cookie：', new_page.headers.get("set-cookie"))
            match = re.search(r"_manatsuku_session=([^;]+)", new_page.headers.get("set-cookie"))
            if match:
                session_value = match.group(1)
                print('manatsuku_session：', session_value)
                self.manatsuku_session = session_value
            # print('Text', new_page_text)
            pattern = r'<input type="hidden" name="authenticity_token" value="([^"]+)"'
            match = re.search(pattern, new_page_text)
            if match:
                authenticity_token = match.group(1)
                print('authenticity_token：', authenticity_token)
                payment_page = self.submi_payment(authenticity_token)
                payment_page_text = payment_page.text
                print('cookie：', payment_page.headers.get("set-cookie"))
                match = re.search(r"_manatsuku_session=([^;]+)", payment_page.headers.get("set-cookie"))
                if match:
                    session_value = match.group(1)
                    print('manatsuku_session：', session_value)
                    self.manatsuku_session = session_value
                # print('Text', payment_page_text)
                print('最后manatsuku_session：', self.manatsuku_session)
                if 'error_explanation' in payment_page_text:
                    pattern = r'<ul id=[\'"]error_explanation[\'"]>\s*<li>([^<]+)</li>\s*</ul>'
                    match = re.search(pattern, payment_page_text)
                    if match:
                        error_message = match.group(1)
                        # print('返回结果：', error_message)
                        if error_message == "このカードでは取引をする事が出来ません。":
                            print(f'绑定结果：{error_message}')
                            print('绑定结果：此卡无法完成交易')
                        else:
                            print(f'绑定结果：{error_message}')
                        return False
                    else:
                        print("错误信息未找到", payment_page_text)
                        return False
                else:
                    # print(payment_page_text)
                    print('未检测到#error_explanation')
                    return True
            else:
                print("authenticity_token获取失败")
                return False


def getTokenUrl(url):
    proxies = {'https': 'http://127.0.0.1:7890'}
    try:
        # 发送HTTP请求获取响应内容
        response = requests.get(url,proxies=proxies, timeout=5,verify=False)
        response.raise_for_status()  # 检查请求是否成功

        # 尝试解析响应内容是否为指定格式
        content = response.text.strip()

        # 使用正则表达式匹配 confirmToken({...}) 这种模式
        pattern = r'confirmToken\(({.*})\)'
        match = re.match(pattern, content)

        if match:
            # 提取JSON部分
            json_str = match.group(1)
            json_data = json.loads(json_str)
            return json_data
        else:
            print("响应内容不符合 confirmToken({...}) 格式")
            return False

    except requests.exceptions.RequestException as e:
        print(f"请求URL时出错: {e}")
        return False
    except json.JSONDecodeError as e:
        print(f"解析JSON时出错: {e}")
        return False

def getGmoToken(cardno, holdername, expire):
    Tdata = {
        "cardno": cardno,
        "expire": expire,
        "holdername": holdername
    }
    try:
        response = requests.get(f"http://121.36.223.161:8000/get_token", params=Tdata)
        response.raise_for_status()
        result = response.json()
        url = result['url']
        print(url)
        token_res = getTokenUrl(url)
        if token_res:
            try:
                token = token_res['tokenObject']["token"]
                return token
            except KeyError:
                return False
        else:
            return False
    except requests.exceptions.RequestException:
        return False

# 示例用法
def main():
    manatsuku_session = 'ZXVZK2RwU0svd0dtM3lwb2d0SWUwSjl4QmFhQWtsalZMWkl1K0V0QkZrMWhKZ3FGaXlqRWM1TTRnRHdZaHJtTmJ5bHExbWVjWFg0QXkvMkxHWUpZWGxIb01INllKeVAzNGxEQjM0Z0NtNGQ4cFpuMStvYjhzalh1dXAxblViRVRjc0RmaDVza0ZzTThmL1ZIU0Erc0JrU0E1TldJQjBETlYzWEU1NEVGMTBwbFRQc3lvQW9hT3d4Z2tUK3g1MDhrRWhNVGFUYU1LOGNLeHVPdnJYazF6TDMrNVlYaEJad3RKTVkxNWlNY01DYU1rS0xTRnRPdlphb1NQdFl0bUd3UjBhSG9vcCszbVp4Yis3a0xWWlRBbC9WQ3JKQlpVZURKMGwvRGxLbml3eEU9LS16ay94ZERnU1lnRGxKb1BBaWZMdnlRPT0%3D--a1a1444b495c3ff88a75586b8edeb1bad25d246a'
    aws_waf_token = 'ea03d638-HEaq4+UrvQbFHylTHT3JDPa6tU5hEfokrkTOZETUjf/WujABZmp0JkRNfrB6Kh51PQ/iEQ2+bV30AXf2fgW2ka/kMHaw/TbjCdUtDQhw+OIuXJoJ44C39OS86IW9nq9zB2IsoE6wTRTAKYgRLOGx/M3W2i1FQEd/LOXmxXefPghmCk2qu5I44pchEgrmyZn2U1RMM8hriv7qyABoP/aaEgt44P+0fzJmJui1ZTI9Mq5FejQwaMao/hn2Muns7p4C'
    card_number = '4147769886918479'
    holder_name = 'Laifhnbn'
    card_company = 'visa'
    expire = '203003'
    ManatSukuApi = ManatSuku(
        manatsuku_session,
        aws_waf_token
    )
    ManatSukuApi.set_proxies(ip, port, proxyUsername, proxyPassword)
    set_gmo = ManatSukuApi.set_gmo_payment(card_number, holder_name, expire, card_company)
    if set_gmo:
        status = ManatSukuApi.main()
        print(status)
    else:
        print('获取gmo_token失败')



if __name__ == "__main__":
    ip = '24fd2a4e70b435d6.xji.na.novada.pro'
    port = '7777'
    proxyUsername = "novada309zkB_ynaP3U-zone-resi-region-jp"
    proxyPassword = "wMiwCpuXV5he"
    # ip = '127.0.0.1'
    # port = '7897'
    # proxyUsername = ''
    # proxyPassword = ''
    main()

